package com.atguigu.exer;

public class ProductTest {
    public static void main(String[] args) {
        Clerk clerk=new Clerk();
        Producer producer=new Producer(clerk);
        Customer1 customer1=new Customer1(clerk);
        producer.setName("生产者");
        customer1.setName("消费者");
        customer1.start();
        producer.start();
    }
}
class Clerk{
    private int number=0;
    //生产产品
    public synchronized void produceProduct() {
        if(number<20){
            number++;
            System.out.println(Thread.currentThread().getName()+":开始生产第"+number+"产品");
            notify();
        }else{
            try {
                wait();
            }catch(InterruptedException e){
                e.printStackTrace();
            }
        }
    }
    //消费产品
    public synchronized void consumeProduct() {
        if(number>0){
            number--;
            System.out.println(Thread.currentThread().getName()+"开始消费第"+number+"产品");
            notify();
        }else{
            try {
                wait();
            }catch (InterruptedException e){
                e.printStackTrace();
            }
        }
    }
}
class Producer extends Thread{//生产者
    private Clerk clerk;
    public Producer(Clerk clerk){
        this.clerk=clerk;
    }
    public void run(){
        System.out.println("生产者开始生产:");
        while (true){
            clerk.produceProduct();
        }
    }
}
class Customer1 extends Thread{
    private Clerk clerk;
    public Customer1(Clerk clerk){
        this.clerk=clerk;
    }

    public void run(){
        while(true){
            clerk.consumeProduct();
        }
    }
}
